import React, { useState, useEffect } from 'react';
import { Button, Form, Input, Checkbox, App } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { login } from '@/services/auth';
import './index.less';

interface LoginForm {
  login_id: string;  // 改为支持多种登录方式
  password: string;
  remember_me?: boolean;
}

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const { message } = App.useApp(); // 使用 App 组件的 message

  // 添加键盘事件监听
  useEffect(() => {
    const handleKeyPress = (e: KeyboardEvent) => {
      if (e.key === 'Enter') {
        form.submit();
      }
    };
    
    document.addEventListener('keypress', handleKeyPress);
    return () => document.removeEventListener('keypress', handleKeyPress);
  }, [form]);

  const onFinish = async (values: LoginForm) => {
    setLoading(true);
    try {
      
      const response = await login(values);
      
      if (response.success) {
        message.success('🚀 登录成功！欢迎进入智能监控系统');
        
        // 保存用户信息和token
        localStorage.setItem('token', response.data!.token);
        localStorage.setItem('user', JSON.stringify(response.data!.user));
        
        // 跳转到项目页面
        setTimeout(() => {
          history.push('/projects');
        }, 800);
      } else {
        message.error(response.message || '登录失败');
      }
    } catch (error: any) {
      console.error('登录错误:', error);
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error('🔧 系统异常，请稍后重试！');
      }
    } finally {
      setLoading(false);
    }
  };

  const goToRegister = () => {
    history.push('/register');
  };

  return (
    <div className="login-container">
      {/* 动态背景 */}
      <div className="login-background">
        <div className="particles"></div>
        <div className="grid-overlay"></div>
      </div>
      
      {/* 主要内容 */}
      <div className="login-content">
        <div className="login-form-wrapper">
          {/* 标题区域 */}
          <div className="login-header">
            <h1 className="login-title">LogWisdomHub</h1>
            <p className="login-subtitle">🔮 智能日志监控系统</p>
            <div className="tech-line"></div>
          </div>
          
          {/* 登录表单 */}
          <Form
            form={form}
            name="login"
            className="login-form"
            onFinish={onFinish}
            autoComplete="off"
            size="large"
          >
            <Form.Item
              name="login_id"
              rules={[{ required: true, message: '请输入用户名、邮箱或手机号!' }]}
            >
              <Input
                className="login-input"
                prefix={<UserOutlined className="input-icon" />}
                placeholder="用户名/邮箱/手机号"
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password
                className="login-input"
                prefix={<LockOutlined className="input-icon" />}
                placeholder="输入密码"
              />
            </Form.Item>

            <Form.Item name="remember_me" valuePropName="checked">
              <Checkbox>记住登录状态</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="login-button"
                loading={loading}
                block
              >
                {loading ? '登录中...' : '立即登录'}
              </Button>
            </Form.Item>

            <div className="login-footer">
              <span>还没有账户？</span>
              <Button type="link" onClick={goToRegister}>
                立即注册
              </Button>
            </div>
          </Form>
        </div>
      </div>
    </div>
  );
};

export default Login;